package com.xm.util;

import com.xm.entity.User;
import com.xm.entity.UserP;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 懒人工具类
 */
@Slf4j
public class CommonUtil {

    private CommonUtil() {
    }

    private static final Random random = new Random();

    /**
     * 获取测试数据
     */
    public static List<User> getUsers(int total, int tag, String mark) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date createTime = sdf.parse(sdf.format(new Date()));
            String createTimeStr = sdf.format(createTime);
            List<User> users = new ArrayList<>();
            User user;
            String height = StringUtil.formatDecimal(random.nextDouble(220), 2, RoundingMode.HALF_UP);
            BigDecimal heightDecimal = BigDecimal.valueOf(Double.parseDouble(height));
            String weight = StringUtil.formatDecimal(random.nextDouble(220), 2, RoundingMode.HALF_UP);
            BigDecimal weightDecimal = BigDecimal.valueOf(Double.parseDouble(weight));
            SimpleDateFormat sdfHms = new SimpleDateFormat("HHmmss");
            String hmsName = sdfHms.format(createTime) + tag;
            String[] markArr = mark.split(" ");
            for (int i = 0; i < total; i++) {
                user = User.builder().name(hmsName + "_" + StringUtil.formatZero(i, 6))
                        .uuid(UUID.randomUUID().toString())
                        .height(heightDecimal)
                        .weight(weightDecimal)
                        .age(random.nextInt(100))
                        .bool(Boolean.TRUE)
                        .signature(markArr[0])
                        .delMark(0)
                        .createTime(createTime)
                        .createTimeStr(createTimeStr)
                        .updateTime(createTime)
                        .updateTimeStr(createTimeStr)
                        .longField("Hello " + mark + "！")
                        .build();
                users.add(user);
            }
            return users;
        } catch (ParseException e) {
            log.error("getUsers 获取用户数据异常！e={}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取测试数据
     */
    public static List<UserP> getUsers2(int total, int tag, String mark) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date createTime = sdf.parse(sdf.format(new Date()));
            String createTimeStr = sdf.format(createTime);
            List<UserP> users = new ArrayList<>();
            UserP user;
            String height = StringUtil.formatDecimal(random.nextDouble(220), 2, RoundingMode.HALF_UP);
            BigDecimal heightDecimal = BigDecimal.valueOf(Double.parseDouble(height));
            String weight = StringUtil.formatDecimal(random.nextDouble(220), 2, RoundingMode.HALF_UP);
            BigDecimal weightDecimal = BigDecimal.valueOf(Double.parseDouble(weight));
            SimpleDateFormat sdfHms = new SimpleDateFormat("HHmmss");
            String hmsName = sdfHms.format(createTime) + tag;
            String[] markArr = mark.split(" ");
            for (int i = 0; i < total; i++) {
                user = UserP.builder().name(hmsName + "_" + StringUtil.formatZero(i, 6))
                        .uuid(UUID.randomUUID().toString())
                        .height(heightDecimal)
                        .weight(weightDecimal)
                        .age(random.nextInt(100))
                        .bool(Boolean.TRUE)
                        .signature("thread " + markArr[0])
                        .delMark(0)
                        .createTime(createTime)
                        .createTimeStr(createTimeStr)
                        .updateTime(createTime)
                        .updateTimeStr(createTimeStr)
                        .longField("Hello thread！" + mark)
                        .build();
                users.add(user);
            }
            return users;
        } catch (ParseException e) {
            log.error("getUsers2 获取用户数据异常！e={}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除数据、释放磁盘空间、并清理日志文件
     */
    public static void clearTable(){
        try (Connection conn = DataSourceUtil.getHikariConnection();) {
            try (Statement statement = conn.createStatement()) {
                statement.executeUpdate("TRUNCATE TABLE `user`");
                statement.execute("OPTIMIZE TABLE `user`");
                statement.execute("RESET MASTER");//清空所有二进制日志（谨慎操作！）
                statement.executeUpdate("PURGE BINARY LOGS BEFORE NOW()");
            }
        } catch (SQLException e) {
            log.error("清理数据异常！e={}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取总记录数
     */
    public static long count(){
        try (Connection conn = DataSourceUtil.getHikariConnection();) {
            try (Statement statement = conn.createStatement()) {
                try (ResultSet rs = statement.executeQuery("SELECT COUNT(1) FROM `user`")) {
                    long count = 0;
                    while (rs.next()) {
                        count = rs.getLong(1);
                    }
                    return count;
                }
            }
        } catch (SQLException e) {
            log.error("获取总记录数异常！e={}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 等待至多线程执行结束
     */
    public static void waitFutures(List<Future<String>> futures) throws ExecutionException, InterruptedException {
        for (Future<String> future : futures) {
            future.get();
        }
    }

}
